<template>
	<view>
		<!-- 立即支付 -->
		<baseHead title="立即支付" bg="#ffffff" color="#000000"></baseHead>
		<view class="card">
			<view class="card-item">
				<view class="card-item-left title">购买内容</view>
				<view class="card-item-right text">{{planInfo.Title}}</view>
			</view>
			<view class="card-item">
				<view class="card-item-left title">支付金额</view>
				<view class="card-item-right price">￥{{planInfo.Price}}</view>
			</view>
		</view>
		<template v-if="!isHiddenPaymentSelect">
			<view class="card-title">
				支付方式
			</view>
			<view class="card">
				<template v-for="item in payments">
					<view class="card-item" @click="handleSelectPayment(item)">
						<view class="card-item-left payment">
							<image class="payment-icon" mode="heightFix"
								:src="`${$config.domain.staticUrl}/static/assets/payment/${item.PaymentMethod}.png`">
							</image>
							<u-text class="payment-name" size="34rpx" color="#000000" :text="item.PaymentName"
								block></u-text>
						</view>
						<view class="card-item-right">
							<label class="radio">
								<radio :value="item.PaymentMethod"
									:checked="currentPaymentMethod==item.PaymentMethod" />
							</label>


						</view>
					</view>
				</template>
			</view>
		</template>

		<view class="containerBottom">
			<view class="fontCla">付费即表示同意<span @click="zengzhi">《慧人才增值服务协议》</span></view>
			<view class="btnCla">
				<u-button type="primary" size="large" :throttleTime="1" color="#3476FE"
					:text="`立即支付 ￥${planInfo.Price}`" :disabled="currentPaymentMethod==0"
					@click="startOrder"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import baseHead from '@/pages/component/baseHead.vue'
	const {
		platform
	} = uni.getSystemInfoSync()
	export default {
		components: {
			baseHead
		},
		data() {
			return {
				payments: [],
				planInfo: null,
				currentPaymentMethod: 0,
				paymentSourceType: 40,
				isHiddenPaymentSelect: false,
				OrderType: 1,
				app: {},
			};
		},
		computed: {
			currentPayment() {
				if (this.payments && this.payments.length > 0)
					return this.payments.find(x => x.PaymentMethod == this.currentPaymentMethod);
				return {}
			}
		},
		onLoad(e) {
			// console.log(JSON.parse(e.tcid ? e.tcid : '{}'))
			console.log(JSON.parse(e.tcid))
			this.planInfo = JSON.parse(e.tcid)

			console.log(this.planInfo)
		},
		created() {
			if (platform == "android") {
				this.paymentSourceType = 30
			} else if (platform == "ios") {
				this.paymentSourceType = 40
			}
			this.app = getApp();
			this.getPayments();
		},
		methods: {
			handleSelectPayment(item) {
				console.log(item, "item");
				this.currentPaymentMethod = item.PaymentMethod + ''
			},
			getPayments() {
				this.$http.digitalize.coursePaymentMethod({
					PaymentSourceType: this.paymentSourceType
				}).then((res) => {
					console.log(res);
					if (res.Success) {
						this.payments = res.Result;
						if (this.payments && this.payments.length > 0) {
							this.currentPaymentMethod = this.payments[0].PaymentMethod
							if (platform == "ios") {
								//特殊处理苹果内购
								this.payments = this.payments.filter(p => p.PaymentMethod == 401)
								if (this.payments.length > 0) {
									this.currentPaymentMethod = 401;
									//this.startOrder()
									this.isHiddenPaymentSelect = true;
								}
							}

						}
					}
				})
			},
			zengzhi() {
				uni.navigateTo({
					url: '/pages/views/packageB/Publicdocuments/zengzhifuwu'
				})
			},

			// 下单支付
			startOrder() {
				let that = this
				const paymentMethod = this.currentPaymentMethod;
				if (paymentMethod == 0) {
					this.$util.toast('请选择支付方式')
					return;
				}
				let obj = {
					// UserId:0,   //用户ID（个人套餐购买，企业ID应为空）
					// CorpId:0,   //购买企业ID（企业套餐购买，用户ID应为空）
					CourseId: this.planInfo.Id, //权益/功能/套餐ID
					OrderSource: 1, //订单来源 1 慧人才 2 平台
					PaymentPlatform: 2, //支付平台 1 web 2 app
					PaymentMethod: paymentMethod,
					OrderType: this.planInfo.OrderType ? this.planInfo.OrderType : this.OrderType
				}
				//userRole == 1招聘者 0求职者
				if (this.app.globalData.userRole == 1) {
					obj.CorpId = this.app.globalData.currentCorp.Id;
				} else if (this.app.globalData.userRole == 0) {
					obj.UserId = this.app.globalData.user.UserId;
				}
				that.$http.digitalize.courseCreate(obj).then((res) => {
					if (!res.Success) {
						that.$util.toast('下单失败')
						return;
					}
					const payData = res.Result.PayData;
					if ([401].includes(paymentMethod)) {
						//苹果内购支付
						const options = {
							productId: that.planInfo.Code ? that.planInfo.Code : that.planInfo.Id,
							quantity: 1,
							outTradeNo: payData.OutTradeNo,
							notifyUrl: payData.NotifyUrl
						}
						uni.navigateTo({
							url: `/pages/views/packageB/Publicdocuments/applepay?p=${JSON.stringify(options)}`
						})
						return;
					}

					//微信支付宝支付
					that.requestPayment(paymentMethod, payData).then(res => {
						//成功
						uni.navigateTo({
							url: '/pages/views/packageB/Publicdocuments/paysuccess'
						})
					}).catch(err => {
						//失败
						uni.navigateTo({
							url: '/pages/views/packageB/Publicdocuments/payfailure'
						})
					})
				})


			},

			requestPayment(paymentMethod, payData) {
				console.log(paymentMethod, "111", payData);
				let provider = undefined;
				let orderInfo = {};

				if (206 == paymentMethod) {
					//WX
					provider = 'wxpay'
					orderInfo = payData
					console.log("进微信");
				} else if (304 == paymentMethod) {
					//支付宝
					provider = 'alipay'
					orderInfo = payData.Body
					console.log("进支付宝");
				} else {
					return Promise.reject("fail：不支持的支付方式");
				}

				uni.showLoading({
					title: '支付处理中...'
				});
				return new Promise((resolve, reject) => {
					console.log("支付---");
					//详见 https://uniapp.dcloud.net.cn/api/plugins/payment.html
					uni.requestPayment({
						provider: provider,
						orderInfo: orderInfo,
						success: (res) => {
							console.log("调起微信成功");
							console.log('success:' + JSON.stringify(res), "成功----");
							resolve(res)
						},
						fail(res) {
							console.log("调起微信失败", res);
							console.log('fail:' + JSON.stringify(err), "失败------");
							reject(res)
						},
						complete() {
							uni.hideLoading()
						}
					})
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.card {
		padding: 30rpx;
		width: 92%;
		border-radius: 40rpx;
		background-color: #FFFFFF;
		margin: 20rpx auto;
		box-sizing: border-box;

		.card-item {
			width: 100%;
			height: 100rpx;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			border-bottom: 1rpx solid #E7E7E8;

			&:last-child {
				border-bottom-width: 0;
				margin-bottom: 0;
			}
		}



		.title {
			font-weight: bold;
			color: #000000;
			font-size: 34rpx;
			min-width: 90px;
		}

		.text {
			white-space: nowrap; //不支持换行
			overflow: hidden; //隐藏多出部分文字
			text-overflow: ellipsis; //用省略号代替多出部分文字
		}

		.price {
			color: #F35370;
		}

		.payment {
			display: flex;
			flex-direction: row;

			.payment-icon {
				height: 46rpx;
				margin-right: 20rpx;
			}

			.payment-name {
				margin-left: 20rpx;
			}
		}
	}

	.card-title {
		width: 92%;
		box-sizing: border-box;
		margin: 40rpx auto 30rpx auto;
		color: #868889;
	}

	.containerBottom {
		width: 92%;
		box-sizing: border-box;
		margin: 80rpx auto 0 auto;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: end;

		.fontCla {
			font-size: 26rpx;

			span {
				color: #3476FE;
			}
		}

		.btnCla {
			margin-top: 40rpx;
			width: 100%;
		}
	}
</style>